package com.example.choupaiapp.main.activity;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.example.choupaiapp.R;
import com.example.choupaiapp.common.constant.Contacts;
import com.example.choupaiapp.common.finalokgo.callback.Callback;
import com.example.choupaiapp.common.finalokgo.request.RequestType;
import com.example.choupaiapp.common.ui.activity.CommonActivity;
import com.example.choupaiapp.common.util.ActivityManager;
import com.example.choupaiapp.common.util.SharedPreferencesHelp;
import com.example.choupaiapp.common.util.Utils;
import com.example.choupaiapp.main.bean.TokenBean;
import com.example.choupaiapp.main.bean.UserInfoBean;
import com.example.choupaiapp.main.constant.Config;
import com.example.choupaiapp.main.constant.Url;
import com.example.choupaiapp.main.view.PhoneEditText;
import com.hyphenate.EMCallBack;
import com.hyphenate.chat.EMClient;
import com.lzy.okgo.model.Response;
import com.orhanobut.logger.Logger;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.analytics.MobclickAgent;
import com.umeng.umverify.UMVerifyHelper;
import com.umeng.umverify.listener.UMPreLoginResultListener;
import com.umeng.umverify.listener.UMTokenResultListener;
import com.umeng.umverify.model.UMTokenRet;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.OnClick;
import cn.jpush.android.api.JPushInterface;

/**
 * Created by ASUS on 2019/10/29.
 */

public class BindPhoneActivity extends CommonActivity {

    @BindView(R.id.phone)
    PhoneEditText phone;
    @BindView(R.id.next)
    TextView next;
    private UMVerifyHelper umVerifyHelper;
    private Bundle bundle;
    private String headUrl = "";
    private String name = "";
    private String openId = "";
    private String flag = "";
    private String sex = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bind_phone);
    }

    @Override
    protected void initView() {

        bundle = getIntent().getExtras();
        if(bundle != null) {
            headUrl = bundle.getString("headUrl");
            name = bundle.getString("name");
            openId = bundle.getString("openId");
            flag = bundle.getString("flag");
            sex = bundle.getString("sex");
        }

        phone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if (phone.getPhoneText().length() == 11) {
                    next.setEnabled(true);
                    next();
                } else {
                    next.setEnabled(false);
                }
            }
        });

    }

    @Override
    protected void initData() {
        UMTokenResultListener umTokenResultListener = new UMTokenResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.e("s:" + s);
                        UMTokenRet tokenRet = null;
                        try {
                            tokenRet = JSON.parseObject(s, UMTokenRet.class);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (tokenRet != null && !("600001").equals(tokenRet.getCode())) {
                            String token = tokenRet.getToken();
                            JSONObject jsonObject = new JSONObject();
                            try {
                                jsonObject.put("mobile",phone.getPhoneText().toString());
                                jsonObject.put("token", token);
                                jsonObject.put("appkey", Config.UMENG_APP_KEY);
                                if (!TextUtils.isEmpty(flag)) {
                                    if (flag.equals("qq")) {
                                        jsonObject.put("qqOpenid", openId);
                                    } else if (flag.equals("weibo")) {
                                        jsonObject.put("sinaOpenid", openId);
                                    } else {
                                        jsonObject.put("wechatOpenid", openId);
                                    }
                                    jsonObject.put("sex", sex);
                                    jsonObject.put("avatar", headUrl);
                                    jsonObject.put("nickname", name);
                                }
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                            finalOkGo.request(RequestType.POSTJSON, Url.RIGIST_LOGIN, null, jsonObject.toString(), new Callback<TokenBean>() {
                                @Override
                                public void onSuccess(TokenBean tokenBean) {
                                    if (tokenBean.getCode() == Contacts.SUCCESS) {
                                        SharedPreferencesHelp.put("token", tokenBean.getToken());
                                        finalOkGo.requestHead(RequestType.GETHEAD, Url.GET_UERINFO, null, Url.GET_UERINFO, new Callback<UserInfoBean>() {
                                            @Override
                                            public void onSuccess(UserInfoBean userInfoBean) {
                                                if (userInfoBean.getCode() == Contacts.SUCCESS) {
                                                    SharedPreferencesHelp.putBean("userInfo", userInfoBean);
                                                    CrashReport.setUserId(context, userInfoBean.getUser().getMobile());
                                                    if (tokenBean.getFirst() == 1) {
                                                        EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                            @Override
                                                            public void onSuccess() {
                                                                umVerifyHelper.hideLoginLoading();
                                                                dismissDialog();
                                                                EMClient.getInstance().groupManager().loadAllGroups();
                                                                EMClient.getInstance().chatManager().loadAllConversations();
                                                                JPushInterface.setAlias(context, 0, Config.JPUS_PRE + userInfoBean.getUser().getUserId());
                                                                MobclickAgent.onProfileSignIn("CP_" + userInfoBean.getUser().getUserId());
                                                                Bundle bundle = new Bundle();
                                                                bundle.putInt("flag", 1);
                                                                startFinishActivity(ChangePersonalInfoActivity.class, bundle);
                                                            }

                                                            @Override
                                                            public void onProgress(int progress, String status) {

                                                            }

                                                            @Override
                                                            public void onError(int code, final String message) {
                                                                runOnUiThread(() -> {
                                                                    Logger.e(code + ":" + message);
                                                                    umVerifyHelper.hideLoginLoading();
                                                                    dismissDialog();
                                                                    JPushInterface.setAlias(context, 0, Config.JPUS_PRE + userInfoBean.getUser().getUserId());
                                                                    MobclickAgent.onProfileSignIn("CP_" + userInfoBean.getUser().getUserId());
                                                                    showImageToas("即时通讯登录失败 私信功能不能使用");
                                                                    Bundle bundle = new Bundle();
                                                                    bundle.putInt("flag", 2);
                                                                    startFinishActivity(ChangePersonalInfoActivity.class, bundle);
                                                                });

                                                            }
                                                        });
                                                    } else {
                                                        EMClient.getInstance().login("HX_" + userInfoBean.getUser().getUserId(), "HX_" + userInfoBean.getUser().getUserId(), new EMCallBack() {//回调
                                                            @Override
                                                            public void onSuccess() {
                                                                umVerifyHelper.hideLoginLoading();
                                                                dismissDialog();
                                                                EMClient.getInstance().groupManager().loadAllGroups();
                                                                EMClient.getInstance().chatManager().loadAllConversations();
                                                                JPushInterface.setAlias(context, 0, Config.JPUS_PRE + userInfoBean.getUser().getUserId());
                                                                MobclickAgent.onProfileSignIn("CP_" + userInfoBean.getUser().getUserId());
                                                                ActivityManager.getActivityManager().popAllActivity();
                                                                startFinishActivity(MainActivity.class);
                                                            }

                                                            @Override
                                                            public void onProgress(int progress, String status) {

                                                            }

                                                            @Override
                                                            public void onError(int code, final String message) {
                                                                runOnUiThread(() -> {
                                                                    Logger.e(code + ":" + message);
                                                                    umVerifyHelper.hideLoginLoading();
                                                                    dismissDialog();
                                                                    JPushInterface.setAlias(context, 0, Config.JPUS_PRE + userInfoBean.getUser().getUserId());
                                                                    MobclickAgent.onProfileSignIn("CP_" + userInfoBean.getUser().getUserId());
                                                                    showImageToas("即时通讯登录失败 私信功能不能使用");
                                                                    ActivityManager.getActivityManager().popAllActivity();
                                                                    startFinishActivity(MainActivity.class);
                                                                });

                                                            }
                                                        });
                                                    }
                                                } else {
                                                    umVerifyHelper.hideLoginLoading();
                                                    dismissDialog();
                                                    if (userInfoBean.getCode() == Contacts.TOKEN_EMPTY) {
                                                    } else {
                                                        showImageToas(userInfoBean.getMsg());
                                                    }
                                                }
                                            }

                                            @Override
                                            public void onError(Response<String> response) {
                                                super.onError(response);
                                                dismissDialog();
                                                umVerifyHelper.hideLoginLoading();
                                            }
                                        });
                                    } else {
                                        umVerifyHelper.hideLoginLoading();
                                        dismissDialog();
                                        if (tokenBean.getCode() == Contacts.TOKEN_EMPTY) {
                                        } else {
                                            showImageToas(tokenBean.getMsg());
                                        }
                                    }
                                }

                                @Override
                                public void onError(Response<String> response) {
                                    super.onError(response);
                                    dismissDialog();
                                    umVerifyHelper.hideLoginLoading();
                                }
                            });
                        }
                    }
                });

            }

            @Override
            public void onTokenFailed(String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        umVerifyHelper.hideLoginLoading();
                    }
                });
            }
        };
        umVerifyHelper = UMVerifyHelper.getInstance(this, umTokenResultListener);
        umVerifyHelper.setAuthSDKInfo(Config.UMENG_SCECET_KEY);
        umVerifyHelper.setAuthListener(umTokenResultListener);
        umVerifyHelper.setLoggerEnable(true);
        umVerifyHelper.accelerateLoginPage(5000, new UMPreLoginResultListener() {
            @Override
            public void onTokenSuccess(String s) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        Logger.e("预取号成功:" + s);
                    }
                });
            }

            @Override
            public void onTokenFailed(String s, String s1) {

            }
        });
    }

//    @Override
    @OnClick({R.id.next})
    public void onViewClicked(View view) {
//        super.onViewClicked(view);
        if (Utils.isDoubleClick()) {
            return;
        }
        switch (view.getId()) {
            case R.id.next:
                next();
                break;
        }
    }

    private void next() {
        if (phone.getPhoneText().length() == 11) {
            boolean check = umVerifyHelper.checkEnvAvailable();
            if (check) {
                umVerifyHelper.getVerifyToken(5000);
            } else {
                showImageToas("请打开您的4g网络");
            }
        } else {
            showImageToas("请输入正确的手机号");
        }
    }
}
